﻿using MediaAdmin.Application.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace MediaAdmin.Application.Data
{
    public class StorageProvider
    {
        public List<LocalFileInfo> GetStorageInfo()
        {
            var list = new List<LocalFileInfo>();

            var path = HttpContext.Current.Request.MapPath("/Content/upload/");
            var di = new DirectoryInfo(path);

            var fi = di.EnumerateFiles().Select(x => new LocalFileInfo() { 
                Name = x.Name, 
                Date = x.CreationTimeUtc, 
                Size = Math.Round(System.Convert.ToDouble(x.Length / 1048576), 2), 
                Path = HttpContext.Current.Request.MapPath("/Content/upload/" + x.Name) }).ToList();

            return fi;
        }

        public void RemoveFile(string name)
        {
            var path = HttpContext.Current.Request.MapPath("/Content/upload/"+name);
            var fi = new FileInfo(path);
            fi.Delete();
        }

        public void UploadFile(string name, bool chunk, byte[] buffer)
        {
            var path = HttpContext.Current.Request.MapPath("/Content/upload/"+name);

            using (var fs = new FileStream(path, chunk ? FileMode.Append : FileMode.Create))
            {
                fs.Write(buffer, 0, buffer.Length);
            }
        }
    }
}